<template>
  <t-dialog
    v-model:visible="visible"
    :header="dialogTitle"
    width="500"
    :confirm-btn="{ loading }"
    @confirm="dialogConfirm"
    @close="dialogHide"
  >
    <t-space direction="vertical" style="width: 100%">
      <t-form ref="form" reset-type="initial" :data="formData" :rules="FORM_RULES">
        <t-form-item :label="t('pages.sitemodel.title')" name="name" initial-data="">
          <t-input v-model="formData.name" maxlength="16" show-limit-number />
        </t-form-item>
        <t-form-item :label="t('pages.sitemodel.table')" name="mark" initial-data="">
          <t-input v-model="formData.mark" maxlength="16" show-limit-number />
        </t-form-item>
        <t-form-item :label="t('common.description')" name="description" initial-data="">
          <t-textarea
            v-model="formData.description"
            :autosize="{ minRows: 3, maxRows: 6 }"
            resize="none"
            maxlength="128"
            show-limit-number
          />
        </t-form-item>
      </t-form>
    </t-space>
  </t-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';

import { t } from '@/locales';

import { FORM_DATA, FORM_RULES, FormItem } from '../constants';

const loading = ref(false);
const emits = defineEmits(['confirm']);

const dialogTitle = ref('');
const type = ref('add');
const visible = ref(false);
const form = ref(null);
const formData = ref({ ...FORM_DATA });

const dialogShow = (action: string, row: FormItem) => {
  visible.value = true;
  type.value = action;
  if (action === 'edit') {
    formData.value = JSON.parse(JSON.stringify(row));
    dialogTitle.value = `${t('common.edit')}【${row.name}】`;
  } else {
    dialogTitle.value = t('common.add');
  }
};
const dialogHide = () => {
  form.value.reset();
  loading.value = false;
  visible.value = false;
};
const dialogConfirm = async () => {
  const valid = await form.value.validate();
  if (valid !== true) {
    return;
  }
  loading.value = true;
  emits('confirm', type.value, formData.value);
};

defineExpose({
  dialogShow,
  dialogHide,
});
</script>
